<template>
	<view class="px-2 py-4">
		<wd-message-box />
		<wd-toast />

		<wd-form ref="auditForm" :model="formData" :rules="formRules">
			<wd-cell-group border>
				<wd-card type="rectangle">
					<template #title>
						<view class="" style="display: flex;">
							<up-avatar :src="globalConfig.appInfo.approvalForm" shape="square"></up-avatar>
							<span style="display: flex;align-items: center;margin-left: 10px;">表单信息</span>
						</view>
					</template>
					<view class="">

						<!-- 动态生成输入项 -->
						<template v-for="item in formFields" :key="item.prop">
							<template v-if="item.visible ? item.visible(formData) : true">
								<!-- input -->
								<wd-input v-if="item.type === 'input'" :label="item.label"
									:label-width="item.labelWidth || '150px'" :prop="item.prop"
									v-model="formData[item.prop]" :placeholder="item.placeholder"
									:type="item.inputType || 'text'" :clearable="item.clearable !== false"
									:disabled="item.disabled === true" />

								<!-- textarea -->
								<wd-textarea v-else-if="item.type === 'textarea'" :label="item.label"
									:label-width="item.labelWidth || '150px'" :prop="item.prop"
									v-model="formData[item.prop]" :placeholder="item.placeholder" auto-height
									:clearable="item.clearable !== false" :disabled="item.disabled === true" />

								<!-- datetime -->
								<wd-datetime-picker v-else-if="item.type === 'datetime'"
									:type="item.datetimeType || 'datetime'" :label="item.label" :prop="item.prop"
									v-model="formData[item.prop]" :placeholder="item.placeholder"
									:disabled="item.disabled === true" />

								<!-- select / selectUser -->
								<wd-select-picker v-else-if="['select', 'selectUser'].includes(item.type)"
									:label="item.label" :label-width="item.labelWidth || '150px'" :prop="item.prop"
									v-model="formData[item.prop]" :columns="item.columns"
									:placeholder="item.placeholder" :multiple="item.multiple ?? false"
									:type="item.multiple ? 'checkbox' : 'radio'" :show-confirm="false"
									:value-key="item.valueKey" :label-key="item.labelKey"
									:clearable="item.clearable !== false" :disabled="item.disabled === true"
									filterable />

								<!-- radio -->
								<wd-cell v-else-if="item.type === 'radio'" :title="item.label"
									:title-width="item.width">
									<wd-radio-group v-model="formData[item.prop]" shape="dot" :inline="item.inline"
										:disabled="item.disabled === true" icon-placement="left" max-width="200"
										@change="item.onChange ? item.onChange(formData[item.prop]) : null"
										:rules="item.rules">
										<wd-radio
											v-for="radio in (typeof item.options === 'function' ? item.options() : item.options)"
											:key="radio[item.optionValue]" :value="radio[item.optionValue]">
											{{ radio[item.optionLabel] }}
										</wd-radio>
									</wd-radio-group>
								</wd-cell>

								<!-- upload -->
								<wd-cell v-else-if="item.type === 'upload'" :title="item.label || '文件上传'"
									title-width="100px">
									<wd-upload v-model:file-list="fileLists[item.prop]" :image-mode="item.imageMode"
										:action="item.action" :limit="item.limit" :accept="item.accept"
										:header="item.header" :disabled="item.disabled === true"
										@success="(response: any) => handleUploadSuccess(item, response)" />
								</wd-cell>

								<!-- rate -->
								<wd-cell v-else-if="item.type === 'rate'" :title="item.title" title-width="100px">
									<wd-rate v-model="formData[item.prop]" size="20px" space="10px" color="#bababa"
										:disabled="item.disabled === true" :active-color="[
											'linear-gradient(180deg, rgba(255,238,0,1) 0%,rgba(250,176,21,1) 100%)',
											'linear-gradient(315deg, rgba(245,34,34,1) 0%,rgba(255,117,102,1) 100%)'
										]" />
								</wd-cell>
							</template>
						</template>
						<!-- 👇 新增：办公用品领用明细子表单 -->
						<wd-card type="rectangle">
							<template #title>
								<view style="display: flex;">
									<up-avatar :src="globalConfig.appInfo.approvalForm" shape="square"></up-avatar>
									<span style="display: flex;align-items: center;margin-left: 10px;">办公用品领用明细</span>
								</view>
							</template>

							<view>
								<view v-for="(item, index) in requisitionDetails" :key="index"
									class="border-b border-gray-200 pb-2 mb-2">
									<wd-input v-model="item.productName" label="品名" label-width="120px"
										placeholder="请输入品名" clearable />
									<wd-input v-model="item.specificationModel" label="规格型号" label-width="120px"
										placeholder="请输入规格型号" clearable />
									<wd-input v-model="item.requestedQuantity" label="领用数量" label-width="120px"
										placeholder="请输入领用数量" clearable />
									<wd-input v-model="item.issuedQuantity" label="实领数量" label-width="120px"
										placeholder="请输入实领数量" clearable />
									<wd-datetime-picker v-model="item.issueDate" label="领用时间" type="date"
										placeholder="选择领用时间" label-width="120px" :default-value="defaulTimetValue" />
									<wd-input v-model="item.remark" label="备注" label-width="120px" placeholder="请输入备注"
										clearable />

									<!-- 删除按钮 -->
									<view class="flex justify-end mt-1">
										<wd-button size="small" type="error"
											@click="handleDeleteDetail(index)">删除</wd-button>
									</view>
								</view>

								<!-- 添加明细按钮 -->
								<view class="flex justify-center mt-3">
									<wd-button type="primary" @click="handleAddDetail" round>+ 添加办公用品领用明细</wd-button>
								</view>
							</view>
						</wd-card>

					</view>
				</wd-card>
			</wd-cell-group>
			<view class="footer" style="margin-top: 30px;">
				<wd-card type="rectangle" v-if="startUserSelectTasks?.length > 0 &&
			(resubmit == 1 || !detailId)">
					<template #title>
						<view class="" style="display: flex;">
							<up-avatar :src="globalConfig.appInfo.approvalTasks" shape="square"></up-avatar>
							<span style="display: flex;align-items: center;margin-left: 10px;">审批流程</span>
						</view>
					</template>
					<view class="">

						<wd-form ref="startUserSelectAssigneesFormRef" :model="startUserSelectAssignees">
							<wd-cell-group border>
								<wd-select-picker :label="`【${userTask.name}】`" label-width="150px"
									v-for="userTask in startUserSelectTasks" :key="userTask.id" :prop="userTask.id"
									v-model="startUserSelectAssignees[userTask.id]" :columns="userOptions"
									placeholder="请选择审批人" clearable filterable required
									:rules="startUserSelectAssigneesFormRules[userTask.id]"></wd-select-picker>
							</wd-cell-group>
						</wd-form>
					</view>
				</wd-card>
				<view class="" style="display: flex;justify-content: space-evenly;margin: 30px 0 20px 0;">
					<wd-button type="success" @click="submitForm" custom-class="custom-shadow" block>提交</wd-button>
					<wd-button type="error" @click="cancelForm" custom-class="custom-shadow" block>取消</wd-button>
				</view>
			</view>
		</wd-form>
	</view>
</template>

<script setup lang="ts">
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import { ref, reactive, nextTick, computed } from 'vue'
	import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
	import { getAccessToken } from '@/utils/auth'
	import * as DefinitionApi from '@/api/bpm/definition'
	import * as UserApi from '@/api/system/user'
	import { getUserProfile, getUserSalary } from "@/api/system/user/profile";
	import { OfficeRequisitionApi, OfficeRequisitionVO } from '@/api/oa/officesuppliesreceived'
	import { useMessage, useToast } from 'wot-design-uni'
	import { formatDate, parseDateToTimestamp } from '@/utils/formatTime'


	const message = useMessage()
	const toast = useToast()
	const globalConfig = (getApp() as any).globalData.config;
	const auditForm = ref() // 表单 Ref
	const detailId = ref(null)
	const resubmit = ref(0)
	const fileList = ref([]) // 文件列表
	const data = ref({ path: '' })
	const defaulTimetValue = ref<number>(Date.now())
	const headerObj = ref(
		{
			Authorization: 'Bearer ' + getAccessToken()
		}
	)

	// 指定审批人
	const processDefineKey = 'oa_officesuppliesreceived' // 流程定义 Key
	const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
	const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
	const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
	const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
	const userOptions = ref<any[]>([]) // 用户列表
	const sealList = ref<any[]>([])


	//表单项字段配置
	const formFields = ref<any[]>([
		{
			type: 'input',
			prop: 'userName',
			label: '领用人',
			placeholder: '请输入领用人',
		},
		{
			type: 'input',
			prop: 'storeroomKeeper',
			label: '库房管理员',
			placeholder: '请输入库房管理员',
		},
		{
			type: 'input',
			prop: 'purchasingManager',
			label: '采购员',
			placeholder: '请输入采购员',
		},
		{
			type: 'input',
			prop: 'remark',
			label: '备注',
			placeholder: '“实领数量”由采购部门填写',
			disabled: true,
		}
	])//表单项字段配置
	const formData = ref<OfficeRequisitionVO>({
	} as any)
	//子表单数据
	const requisitionDetails = ref<any[]>([])
	const formRules = reactive({
		userName: [
			{ required: true, message: '请输入领用人', trigger: 'blur' }
		],
	})


	const handleAddDetail = () => {
		requisitionDetails.value.push({
			productName: '',
			specificationModel: '',
			requestedQuantity: '',
			issuedQuantity: '',
			issueDate: '',
			remark: ''
		})
	}

	const handleDeleteDetail = (index : number) => {
		requisitionDetails.value.splice(index, 1)
	}
	onLoad(async (options) => {
		const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
			undefined,
			processDefineKey
		)
		if (!processDefinitionDetail) {
			toast.error('流程模型未配置，请检查！')
			return
		}
		startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
		console.log('startUserSelectTasks', processDefinitionDetail)
		// 设置指定审批人
		if (startUserSelectTasks.value?.length > 0) {
			// 设置校验规则
			for (const userTask of startUserSelectTasks.value) {
				startUserSelectAssignees.value[userTask.id] = []
				startUserSelectAssigneesFormRules.value[userTask.id] = [
					{

						required: true,
						message: '请选择审批人',
						validator: (value : any) => {
							console.log("当前审批人值435435:", value); // 调试输出
							if (value && Array.isArray(value) && value.length > 0) {
								console.log('value.length', value.length);
								return Promise.resolve();
							} else {
								return Promise.reject('审批人不能为空');
							}
						},
						trigger: ['change']

					}
				]
			}
			console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);
			console.log('startUserSelectAssigneesFormRules.value', startUserSelectAssigneesFormRules.value);
		}
		detailId.value = options?.id
		resubmit.value = options?.resubmit
		console.log('detailId.value', detailId.value);
		console.log('resubmit.value', resubmit.value);
		/** 获得详情 */
		if (detailId.value) { getDetailById() }
		// 加载用户列表
		getUserList()
	})




	//附件图片/文档数据回显
	function buildFileList(attachments : string | string[] | undefined) : { url : string, name ?: string }[] {
		if (!attachments) return [];

		const toFileObj = (url : string) => ({
			url,
			name: url.split('/').pop() || '附件'
		});

		if (Array.isArray(attachments)) {
			return attachments.map(toFileObj);
		} else {
			return [toFileObj(attachments)];
		}
	}
	/** 获取页面详情 */
	const getDetailById = async () => {
		try {
			const data = await OfficeRequisitionApi.getOfficeRequisition(Number(detailId.value))
			formData.value = data
			if (formData.value.id) {
				requisitionDetails.value = await OfficeRequisitionApi.getOfficeRequisitionDetailsListByOsrId(formData.value.id)
				console.log('requisitionDetails.value', requisitionDetails.value);
				requisitionDetails.value = requisitionDetails.value.map(item => ({
					...item,
					issueDate: item.issueDate ? parseDateToTimestamp(item.issueDate) : null
				}))

			}
			// 附件字段回显
			fileList.value = buildFileList(data.ename) as any;
			console.log('formData.value', formData.value);
		} catch (error) {
			console.log('加载数据失败')
		}
	}
	/** 获取用户列表 */
	const getUserList = async () => {
		try {
			const userList = await UserApi.getSimpleUserList();
			userOptions.value = userList.map((item : any) => ({
				value: item.id,
				label: item.nickname,
				// id: item.id,
				// name: item.nickname
			}));
		} catch (error) {
			console.error("获取用户列表失败:", error);
			userOptions.value = []; // 失败时，防止 userOptions.value 变成 undefined
		}
	}

	/** 提交表单 */
	const submitForm = async () => {
		console.log('formData.value', formData.value);

		// 校验表单
		const { valid, errors } = await auditForm.value.validate();
		if (!valid) {
			console.log('表单校验未通过:', errors);
			return; // ✅ 校验失败，终止后续代码
		}
		// 校验指定审批人

		if (startUserSelectTasks.value?.length > 0 &&
			(resubmit.value == 1 || !detailId.value)) {
			console.log('校验了吗');
			if (!startUserSelectAssigneesFormRef.value) {
				throw new Error('审批人表单未初始化')
			}
			console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);

			const { valid, errors } = await startUserSelectAssigneesFormRef.value.validate();
			if (!valid) {
				console.log('表单校验未通过:', errors);
				console.log('errors:', errors);
				return; // ✅ 校验失败，终止后续代码
			}
		}
		try {
			const data = formData.value as unknown as OfficeRequisitionVO
			// 拼接子表的数据
			data.officeRequisitionDetailss = requisitionDetails.value
			// 设置指定审批人
			if (startUserSelectTasks.value?.length > 0) {
				data.startUserSelectAssignees = startUserSelectAssignees.value
			}
			if (detailId.value) {
				// 编辑模式
				await OfficeRequisitionApi.updateOfficeRequisition(data)
				toast.success('编辑成功')
			}
			else {
				// 新增模式
				console.log('data', data);
				await OfficeRequisitionApi.createOfficeRequisition(data)
				toast.success('新增成功')

			}
			uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/officesuppliesreceived/index' });
		} catch {
			console.log('error');
		}
	}
	/** 取消表单 */
	const cancelForm = async () => {
		try {
			// 删除的二次确认
			await message.confirm({
				msg: '您确定要取消吗？',
				title: '提示'  // 添加标题
			})
			uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/officesuppliesreceived/index' });
			// 显示成功提示
			toast.success('取消成功')
		} catch (error) {
			console.log('用户取消了操作或发生错误:', error)
		}
	}
</script>

<style scoped lang="scss">
	.container {
		padding: 20px 5px;
	}

	.custom-shadow {
		width: 40%;
		border-radius: 5%;
	}
</style>